"""
根据账号获取用户对象


"""
import re
from django.contrib.auth.backends import ModelBackend
from .models import User
from rest_framework.views import APIView
from rest_framework.response import Response


def get_user_by_account(account):
    """
    根据账号获取用户对象
    :param account: 用户名或者手机号
    :return: user对象 或 提示：用户不存在
    """

    try:
        #     判断是否是手机号码
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(phone=account)


        else:
            user = User.objects.get(username=account)

    except User.DoesNotExist:
        return None

    else:
        return user


# 自定义认证方式，重写原来的认证规则
class UsernamePhoneAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user


class PhoneApiView(APIView):
    def get(self, request, phone):
        ret = get_user_by_account(phone)
        if ret is not None:
            # 判断用户是否已经存在
                return Response({"message": "手机号码已经被注册过了！"}, status=400)

        return Response({'message': 'ok'})
